package com.education.ai.service.impl;

import com.education.ai.service.TeachingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Arrays;
import java.math.BigDecimal;

/**
 * 教学服务实现类
 */
@Service
public class TeachingServiceImpl implements TeachingService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取教师个人资料
     *
     * @param teacherId 教师ID
     * @return 教师个人资料
     */
    @Override
    public Map<String, Object> getTeacherProfile(String teacherId) {
        // 实际项目中应该从数据库中查询
        Map<String, Object> profile = new HashMap<>();
        profile.put("id", teacherId);
        profile.put("name", "教师" + teacherId);
        profile.put("subject", "数学");
        profile.put("school", "示例中学");
        return profile;
    }

    /**
     * 更新教师个人资料
     *
     * @param profileData 教师个人资料
     */
    @Override
    public void updateTeacherProfile(Map<String, Object> profileData) {
        // 实际项目中应该更新数据库
        System.out.println("更新教师资料: " + profileData);
    }

    /**
     * 获取学生历次考试记录
     *
     * @param studentId 学生ID
     * @return 学生历次考试记录
     */
    @Override
    public List<Map<String, Object>> getStudentExamRecords(String studentId) {
        try {
            System.out.println("查询学生 " + studentId + " 的考试记录");
            
            // 查询学生的所有考试记录，按考试时间降序排序
            String examRecordsSql = "SELECT * FROM exam_records WHERE student_id = ? ORDER BY exam_time DESC";
            List<Map<String, Object>> examRecords = jdbcTemplate.queryForList(examRecordsSql, studentId);
            
            System.out.println("学生 " + studentId + " 有 " + examRecords.size() + " 条考试记录");
            
            // 确保返回的数据字段名与前端一致
            for (Map<String, Object> record : examRecords) {
                // 修正字段名 - exam_name -> examName
                if (record.containsKey("exam_name") && !record.containsKey("examName")) {
                    record.put("examName", record.get("exam_name"));
                }
                
                // 修正字段名 - exam_time -> examTime
                if (record.containsKey("exam_time") && !record.containsKey("examTime")) {
                    record.put("examTime", record.get("exam_time"));
                }
                
                // 修正字段名 - total_score -> totalScore
                if (record.containsKey("total_score") && !record.containsKey("totalScore")) {
                    record.put("totalScore", record.get("total_score"));
                }
            }
            
            return examRecords;
        } catch (Exception e) {
            System.out.println("查询学生 " + studentId + " 的考试记录失败: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    /**
     * 根据班级名称获取学生列表
     *
     * @param className 班级名称
     * @return 学生列表
     */
    @Override
    public List<Map<String, Object>> getStudentsByClassName(String className) {
        try {
            System.out.println("根据班级名称查询学生: " + className);
            
            // 查询指定班级的所有学生
            String studentsSql = "SELECT * FROM students WHERE class_name = ? ORDER BY student_id";
            List<Map<String, Object>> students = jdbcTemplate.queryForList(studentsSql, className);
            
            System.out.println("班级 " + className + " 有 " + students.size() + " 名学生");
            
            // 确保返回的数据字段名与前端一致
            for (Map<String, Object> student : students) {
                // student_id -> studentId
                if (student.containsKey("student_id") && !student.containsKey("studentId")) {
                    student.put("studentId", student.get("student_id"));
                }
                
                // class_name -> className
                if (student.containsKey("class_name") && !student.containsKey("className")) {
                    student.put("className", student.get("class_name"));
                }
            }
            
            return students;
        } catch (Exception e) {
            System.out.println("查询班级 " + className + " 的学生列表失败: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    /**
     * 添加考试记录，使用UPSERT方式处理，同一学生同一考试仅有一条记录
     *
     * @param examData 考试数据，包含examName、examTime、students等
     */
    @Override
    public void addExamRecords(Map<String, Object> examData) {
        try {
            System.out.println("添加考试记录: " + examData);
            
            String examName = (String) examData.get("examName");
            Object examTimeObj = examData.get("examTime");
            
            // 处理考试时间
            java.sql.Date examDate;
            if (examTimeObj instanceof Date) {
                examDate = new java.sql.Date(((Date) examTimeObj).getTime());
            } else if (examTimeObj instanceof String) {
                // 尝试解析日期字符串
                try {
                    // 尝试ISO格式
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    Date parsedDate = sdf.parse((String) examTimeObj);
                    examDate = new java.sql.Date(parsedDate.getTime());
                } catch (Exception e) {
                    // 尝试纯日期格式
                    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("yyyy-MM-dd");
                    Date parsedDate = sdf2.parse((String) examTimeObj);
                    examDate = new java.sql.Date(parsedDate.getTime());
                }
            } else {
                // 默认使用当前日期
                examDate = new java.sql.Date(System.currentTimeMillis());
            }
            
            // 获取学生成绩数据
            List<Map<String, Object>> students = (List<Map<String, Object>>) examData.get("students");
            
            if (students == null || students.isEmpty()) {
                throw new IllegalArgumentException("考试记录中没有学生数据");
            }
            
            // 处理每个学生的成绩
            for (Map<String, Object> student : students) {
                String studentId = (String) student.get("studentId");
                
                if (studentId == null || studentId.isEmpty()) {
                    System.out.println("警告: 跳过无效的学生ID: " + student);
                    continue;
                }
                
                // 识别当前学科字段
                Map<String, Object> subjectFields = new HashMap<>();
                List<String> allSubjects = Arrays.asList(
                    "chinese", "math", "english", "physics", "chemistry", 
                    "biology", "politics", "history", "geography"
                );
                
                // 只收集存在于请求中的学科字段
                for (String subject : allSubjects) {
                    if (student.containsKey(subject)) {
                        subjectFields.put(subject, student.get(subject));
                        // 也检查并收集备注字段
                        String remarkField = subject + "_remarks";
                        if (student.containsKey(remarkField)) {
                            subjectFields.put(remarkField, student.get(remarkField));
                        } else {
                            subjectFields.put(remarkField, null);
                        }
                    }
                }
                
                if (subjectFields.isEmpty()) {
                    System.out.println("警告: 没有找到学科成绩字段，跳过学生: " + studentId);
                    continue;
                }
                
                try {
                    // 尝试使用UPSERT
                    performUpsertOperation(studentId, examName, examDate, subjectFields);
                } catch (Exception e) {
                    // 检查是否是DUPLICATE_RECORD_FOUND错误
                    if (e.getMessage() != null && e.getMessage().contains("DUPLICATE_RECORD_FOUND")) {
                        System.out.println("检测到重复记录错误，尝试直接更新: " + e.getMessage());
                        
                        // 获取已存在的记录ID
                        try {
                            // 查询现有记录获取ID
                            String query = "SELECT id FROM exam_records WHERE student_id = ? AND exam_name = ?";
                            List<Map<String, Object>> records = jdbcTemplate.queryForList(query, studentId, examName);
                            
                            if (!records.isEmpty()) {
                                Object existingId = records.get(0).get("id");
                                if (existingId != null) {
                                    // 构建更新请求
                                    Map<String, Object> updateRequest = new HashMap<>();
                                    updateRequest.put("examId", existingId);
                                    updateRequest.put("studentId", studentId);
                                    
                                    // 添加要更新的学科字段
                                    for (Map.Entry<String, Object> entry : subjectFields.entrySet()) {
                                        updateRequest.put(entry.getKey(), entry.getValue());
                                    }
                                    
                                    // 执行更新
                                    updateExamRecord(updateRequest);
                                    System.out.println("已成功更新学生 " + studentId + " 的考试记录");
                                    continue;
                                }
                            }
                        } catch (Exception queryEx) {
                            System.out.println("尝试查询和更新已存在记录失败: " + queryEx.getMessage());
                            queryEx.printStackTrace();
                        }
                    }
                    
                    // 抛出原始异常
                    throw e;
                }
            }
            
            System.out.println("成功处理考试记录");
        } catch (Exception e) {
            System.out.println("添加考试记录失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("添加考试记录失败", e);
        }
    }
    
    /**
     * 执行UPSERT操作
     */
    private void performUpsertOperation(String studentId, String examName, java.sql.Date examDate, 
                                        Map<String, Object> subjectFields) {
        // 构建UPSERT SQL
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO exam_records (student_id, exam_name, exam_date, exam_time");
        
        // 添加所有字段名
        for (String field : subjectFields.keySet()) {
            sql.append(", ").append(field);
        }
        
        sql.append(", created_at, updated_at) VALUES (?, ?, ?, ?");
        
        // 为每个字段添加占位符
        for (int i = 0; i < subjectFields.size(); i++) {
            sql.append(", ?");
        }
        
        sql.append(", NOW(), NOW()) ON DUPLICATE KEY UPDATE ");
        
        // 添加所有需要更新的字段
        int i = 0;
        for (String field : subjectFields.keySet()) {
            if (i > 0) {
                sql.append(", ");
            }
            sql.append(field).append(" = VALUES(").append(field).append(")");
            i++;
        }
        
        // 同时更新时间戳
        sql.append(", updated_at = NOW()");
        
        // 准备参数列表
        List<Object> params = new ArrayList<>();
        params.add(studentId);
        params.add(examName);
        params.add(examDate);
        params.add(examDate); // 同样的值添加到exam_time字段
        
        // 添加所有字段的值
        for (String field : subjectFields.keySet()) {
            Object value = subjectFields.get(field);
            if (field.endsWith("_remarks")) {
                // 备注字段可以为null或字符串
                params.add(value);
            } else {
                // 学科成绩转换为BigDecimal
                params.add(convertToBigDecimal(value));
            }
        }
        
        // 执行UPSERT
        int updated = jdbcTemplate.update(sql.toString(), params.toArray());
        System.out.println("UPSERT操作对学生 " + studentId + " 的考试记录影响了 " + updated + " 行");
        
        // 更新总分
        String updateTotalSql = "UPDATE exam_records SET total_score = " +
            "(COALESCE(chinese, 0) + COALESCE(math, 0) + COALESCE(english, 0) + " +
            "COALESCE(politics, 0) + COALESCE(history, 0) + COALESCE(geography, 0) + " +
            "COALESCE(physics, 0) + COALESCE(chemistry, 0) + COALESCE(biology, 0)) " +
            "WHERE student_id = ? AND exam_name = ?";
        jdbcTemplate.update(updateTotalSql, studentId, examName);
    }
    
    /**
     * 更新考试记录
     *
     * @param updateData 更新数据，包含examId、studentId和所需更新的学科成绩
     */
    @Override
    public void updateExamRecord(Map<String, Object> updateData) {
        try {
            System.out.println("更新考试记录: " + updateData);
            
            Object examIdObj = updateData.get("examId");
            String studentId = (String) updateData.get("studentId");
            
            // 检查必要参数
            if (examIdObj == null) {
                throw new IllegalArgumentException("缺少考试ID");
            }
            
            if (studentId == null || studentId.isEmpty()) {
                throw new IllegalArgumentException("缺少学生ID");
            }
            
            // 转换examId为长整型
            Long examId;
            if (examIdObj instanceof Long) {
                examId = (Long) examIdObj;
            } else if (examIdObj instanceof Integer) {
                examId = ((Integer) examIdObj).longValue();
            } else if (examIdObj instanceof String) {
                examId = Long.parseLong((String) examIdObj);
            } else {
                throw new IllegalArgumentException("无效的考试ID格式");
            }
            
            // 构建更新SQL和参数
            StringBuilder updateSql = new StringBuilder("UPDATE exam_records SET updated_at = NOW()");
            List<Object> params = new ArrayList<>();
            
            // 检查是否需要更新考试时间
            if (updateData.containsKey("examTime")) {
                String examTimeStr = (String) updateData.get("examTime");
                if (examTimeStr != null && !examTimeStr.isEmpty()) {
                    try {
                        // 解析日期字符串
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                        java.util.Date date = sdf.parse(examTimeStr);
                        
                        // 更新exam_time和exam_date字段
                        updateSql.append(", exam_time = ?");
                        params.add(new java.sql.Date(date.getTime()));
                        
                        updateSql.append(", exam_date = ?");
                        params.add(examTimeStr);
                        
                        System.out.println("更新考试日期为: " + examTimeStr);
                    } catch (Exception e) {
                        System.out.println("日期解析错误: " + e.getMessage());
                        throw new IllegalArgumentException("无效的日期格式，应为YYYY-MM-DD", e);
                    }
                }
            }
            
            // 检查是否有各学科成绩需要更新
            String[] subjects = {"chinese", "math", "english", "politics", "history", 
                               "geography", "physics", "chemistry", "biology"};
            for (String subject : subjects) {
                if (updateData.containsKey(subject)) {
                    updateSql.append(", ").append(subject).append(" = ?");
                    params.add(convertToBigDecimal(updateData.get(subject)));
                }
                
                // 检查学科备注是否需要更新
                String remarkField = subject + "_remarks";
                if (updateData.containsKey(remarkField)) {
                    updateSql.append(", ").append(remarkField).append(" = ?");
                    params.add(updateData.get(remarkField));
                }
            }
            
            // 添加条件参数
            updateSql.append(" WHERE id = ? AND student_id = ?");
            params.add(examId);
            params.add(studentId);
            
            // 执行更新
            int updated = jdbcTemplate.update(updateSql.toString(), params.toArray());
            
            if (updated > 0) {
                System.out.println("成功更新考试记录: examId=" + examId + ", studentId=" + studentId);
                
                // 更新总分
                String updateTotalSql = "UPDATE exam_records SET total_score = " +
                    "(COALESCE(chinese, 0) + COALESCE(math, 0) + COALESCE(english, 0) + " +
                    "COALESCE(politics, 0) + COALESCE(history, 0) + COALESCE(geography, 0) + " +
                    "COALESCE(physics, 0) + COALESCE(chemistry, 0) + COALESCE(biology, 0)) " +
                    "WHERE id = ?";
                jdbcTemplate.update(updateTotalSql, examId);
            } else {
                System.out.println("未找到要更新的考试记录: examId=" + examId + ", studentId=" + studentId);
            }
        } catch (Exception e) {
            System.out.println("更新考试记录失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("更新考试记录失败", e);
        }
    }
    
    /**
     * 删除考试记录
     *
     * @param deleteData 删除数据，包含examId和studentId
     */
    @Override
    public void deleteExamRecord(Map<String, Object> deleteData) {
        try {
            System.out.println("删除考试记录: " + deleteData);
            
            Object examIdObj = deleteData.get("examId");
            String studentId = (String) deleteData.get("studentId");
            
            // 检查必要参数
            if (examIdObj == null) {
                throw new IllegalArgumentException("缺少考试ID");
            }
            
            if (studentId == null || studentId.isEmpty()) {
                throw new IllegalArgumentException("缺少学生ID");
            }
            
            // 转换examId为长整型
            Long examId;
            if (examIdObj instanceof Long) {
                examId = (Long) examIdObj;
            } else if (examIdObj instanceof Integer) {
                examId = ((Integer) examIdObj).longValue();
            } else if (examIdObj instanceof String) {
                examId = Long.parseLong((String) examIdObj);
            } else {
                throw new IllegalArgumentException("无效的考试ID格式");
            }
            
            // 执行删除
            String deleteSql = "DELETE FROM exam_records WHERE id = ? AND student_id = ?";
            int deleted = jdbcTemplate.update(deleteSql, examId, studentId);
            
            if (deleted > 0) {
                System.out.println("成功删除考试记录: examId=" + examId + ", studentId=" + studentId);
            } else {
                System.out.println("未找到要删除的考试记录: examId=" + examId + ", studentId=" + studentId);
            }
        } catch (Exception e) {
            System.out.println("删除考试记录失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("删除考试记录失败", e);
        }
    }
    
    /**
     * 将对象转换为BigDecimal
     *
     * @param obj 要转换的对象
     * @return BigDecimal值，如果无法转换则返回null
     */
    private BigDecimal convertToBigDecimal(Object obj) {
        if (obj == null) {
            return null;
        }
        
        try {
            if (obj instanceof BigDecimal) {
                return (BigDecimal) obj;
            } else if (obj instanceof Number) {
                return new BigDecimal(((Number) obj).toString());
            } else if (obj instanceof String) {
                if (((String) obj).isEmpty()) {
                    return null;
                }
                return new BigDecimal((String) obj);
            }
        } catch (NumberFormatException e) {
            System.out.println("无法转换为数字: " + obj);
        }
        
        return null;
    }
} 